var userId=0;
function PageInit(){
    if(com_obj.userId>=0){
        userId=com_obj.userId;
    }
    getAddressList();
    getAddress();
}
var vm=new Vue({
    el: '#address',
    data: {
        addressList: [],
        addressObj: {},      //收货地址
        editAddress: {},     //要编辑的地址
        addressInfo_list: [],
        citysList: [],                 //城市列表
        areasList: [],                 //地区列表
        proSelected: -1,               //选中省时
        citySelected: -1,              //选中市时
        areaSelected: -1,              //选中地区时
        proName: '请选择',              //省名
        cityName: '请选择',             //市名
        areaName: '请选择',             //地区名
        selected: 1,
    },
    methods: {
        //编辑地址
        editAddressFun: function (item) {
            var _this = this;
            $('.addressName').text('修改地址');
            editBtn();
            _this.editAddress = item;
            _this.editAddress.addressInf = item.province + ' ' + item.city + ' ' + item.area + ' ';
            if ((item.isDefault - 0) == 1) {
                //说明是默认地址
                $('.m-switch').prop('checked', true);
                _this.defaultId = 1;
            } else {
                //说明不是默认地址
                $('.m-switch').prop('checked', false);
                _this.defaultId = 0;
            }
            actionType = 1;

        },
        //设为默认地址
        setDefaultFun: function () {
            var _this = this;
            if ($('.m-switch').is(':checked')) {
                //设为默认
                _this.defaultId = 1;
            } else {
                //不设置为默认
                _this.defaultId = 0;
            }
        },
        //删除地址
        delAddressFun: function (item) {
            var _this = this;
            _this.userAddressId = item.userAddressId;
            delAddress();
        },
        //在地址列表中设置收货地址
        setUserAddress:function(item) {
            var _this = this;
            _this.addressObj = item;
            userlatitude = item.lat;
            userlongitude = item.lon;
            _this.selectedYesNO = true;
            _this.addressNull = false;      //显示配送方式
            $('.null-address-box').hide();
            $('.exist-address-box').show();
            vm.addressObj.province = item.province;   //切换地址   省份改变   则邮费改变
            //重新设置收货地址  运费接口  去结算商品数据接口都要重新请求一次
            getPayGoodsData();    //去结算商品数据里包含请求邮费接口

            returnPayPage(1);
        },
        getCitys: function (c, index) {
            //点击省   得到所在省的所有城市

            vm.citysList = c.citys;
            vm.proSelected = index;
            vm.citySelected = -1;
            vm.proName = c.proName;
            vm.cityName = '请选择';
            vm.areaName = '请选择';
            vm.selected = 2;
        },
        //得到所在城市的所有区县
        getAreas: function (a, index) {
            vm.areasList = a.areas;
            vm.cityName = a.cityName;
            vm.areaName = '请选择';
            vm.citySelected = index;
            vm.areaSelected = -1;
            vm.selected = 3;
            $('.destination').css({
                overflow: 'visible'
            })
            $('.destination ').animate({
                left: -bw * 0.5,
            })
        },
        //关闭地址联动以及遮罩
      closeDestination:function(s,index){
            vm.areaSelected=index;
            $('.destination').slideToggle()
            vm.areaName= s.areaName;
            vm.editAddress.addressInf = vm.proName + ' ' + vm.cityName + ' ' + vm.areaName +' ';
            $('#my_inf').show();
            closeBg();
            $('.destination ').animate({
                left:0,
                bottom:0
            })
        }
    }
})

//在添加地址市选择省市区
var $address = $('#my_Address');
$address.citySelect();
$address.on('click', function (event){
    event.stopPropagation();

    $('.destination').slideToggle();
    showBg();

    //$address.citySelect('open');
});

//获取地址列表
var AddressPageNum = 1;
var AddressPageSize = 10;
var AddressLoading = false;
function getAddressList(){
    $.ajaxHandler({
        model: function () {
            var obj={};
            obj.page = AddressPageNum;
            obj.pageSize = AddressPageSize;
            obj.userId = userId;
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        //approve:true,
        visible:'hide',
        api:'yg_baijiaapporder/userAddress/listUserAddressPage',
        success: function(result){
            if(result.code == 10000){
                var data = result.data;
                if(data.length > 0){
                    //说明有地址
                    AddressLoading = false;
                    data.forEach(function(value,index){
                        vm.addressList.push(value);
                    });
                    $('.addreddbg').hide();
                }else {
                    AddressLoading = true;
                    if(AddressPageNum == 1){
                        $('.addreddbg').show();
                        //$('.addreddbg').hide();

                    }else {
                        YDUI.dialog.toast('加载完啦~', 'none', 1000);
                    }
                }
            }else {
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    })
}
//添加新地址页面
function setNewAddress(){
    $('.addressName').text('添加地址');
    $('.payContent').hide();
    $('.address-add').show();
    $('.myAddress-wrap').hide();
    $('.seleAddress').hide();
    addListPage = false;
    actionType = 2;
    vm.editAddress = {};
    $('.m-switch').prop('checked',false);
    $('#my_inf').hide();
    vm.defaultId = 0;   //默认是  不设置为默认地址
    //setPlaceFun();
}


//获取默认地址
function getDefaultAddress(){
    $.ajaxHandler({
        model: function () {
            var obj={};
            obj.userId = userId;
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        api: 'yg_baijiaapporder/userAddress/selectDefaultAddress',
        success: function (result) {
            if(result.code == 10000){
                var data = result.data;
                $('.null-address-box').hide();
                $('.exist-address-box').show();
                vm.addressObj = data;
                vm.addressNull = false;
                userlatitude=data.lat;
                userlongitude=data.lon;
                getPayGoodsData();   //去结算商品数据


            }else if(result.code == 20129){
                $('.null-address-box').show();
                $('.exist-address-box').hide();
                vm.addressObj = {};
                vm.addressNull = true;
                getPayGoodsData();   //去结算商品数据

            } else {
                vm.addressObj = {};
                vm.addressNull = true;
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    })
}

function geocoder() {
    var geocoder = new AMap.Geocoder({
//            city: "010", //城市，默认：“全国”
//            radius: 1000 //范围，默认：500
    });
    //地理编码,返回地理编码结果
    geocoder.getLocation(addressInfo, function(status, result) {
        console.log(result)
        if (status==='complete' && result.info === 'OK') {
            var geocode = result.geocodes;
            geocode.forEach(function(value,index){
                addresslat=value.location.lat;
                addresslon=value.location.lng;
                console.log(addresslat)
                console.log(addresslon)
                saveAddress();
            })
        }
    });
}
function addMarker(i, d) {
    var marker = new AMap.Marker({
        map: map,
        position: [ d.location.getLng(),  d.location.getLat()]
    });
    var infoWindow = new AMap.InfoWindow({
        content: d.formattedAddress,
        offset: {x: 0, y: -30}
    });
    marker.on("mouseover", function(e) {
        infoWindow.open(map, marker.getPosition());
    });
}
//修改(添加)地址
function editFun(){
    if(vm.editAddress.linkMan=='' || typeof (vm.editAddress.linkMan) == 'undefined'){
        YDUI.dialog.toast('请输入收货人', 'none', 1000);
    }else if(vm.editAddress.mobile == '' || typeof (vm.editAddress.mobile) == 'undefined'){
        YDUI.dialog.toast('请输入手机号码', 'none', 1000);
    }else if(vm.editAddress.addressInf == '' || typeof (vm.editAddress.addressInf) == 'undefined'){
        YDUI.dialog.toast('请选择省/市/区', 'none', 1000);
    }else if(vm.editAddress.address == '' || typeof (vm.editAddress.address) == 'undefined'){
        YDUI.dialog.toast('请输入详细地址', 'none', 1000);
    }else if(vm.editAddress.idNumber != ''&& typeof (vm.editAddress.idNumber) != 'undefined'){
        //如果填写身份证的话  就验证 否则就不验证
        if(vm.editAddress.idNumber.length == 15 || vm.editAddress.idNumber.length == 18){
            addressInfo=vm.editAddress.addressInf+vm.editAddress.address;
            geocoder();
        }else {
            $('.idNumber-tex i').show();
        }
    }else {
        addressInfo=vm.editAddress.addressInf+vm.editAddress.address;
        geocoder();
    }
}

//保存修改(添加)之后的地址
function saveAddress(){
    var obj = {};
    obj.address = vm.editAddress.address;
    obj.province = vm.editAddress.addressInf.split(' ')[0];   //省份
    obj.city = vm.editAddress.addressInf.split(' ')[1];     //市
    obj.area = vm.editAddress.addressInf.split(' ')[2];     //区
    obj.isDefault = vm.defaultId;
    obj.linkMan = vm.editAddress.linkMan;
    obj.mobile = vm.editAddress.mobile;
    obj.idNumber = vm.editAddress.idNumber;
    obj.userId = userId;
    obj.lon=addresslon;
    obj.lat=addresslat;
    obj.street = '';
    if(actionType == 1){
        //编辑地址
        obj.id = vm.editAddress.userAddressId;
        $.ajaxHandler({
            model: function () {
                console.log(obj);
                return obj;
            },
            visibleTime: 0,
            dataType: "json",
            api: 'yg_baijiaapporder/userAddress/changeUseraddressByuserId',
            success: function (result) {
                if(result.code == 10000){
                    reAddressPage();        //回到地址列表页面
                    AddressPageNum = 1;     //获取地址列表从第一页开始
                    vm.addressList = [];
                    getAddressList();       //重新加载地址列表
                    //如果编辑的地址是当前选择的地址  编辑保存之后更新选择的地址
                    if(vm.editAddress.userAddressId == vm.addressObj.userAddressId){
                        vm.addressObj = vm.editAddress;
                    }

                }else {
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        })
    }else if(actionType == 2){
        //添加地址
        $.ajaxHandler({
            model: function () {
                return obj;
            },
            visibleTime: 0,
            dataType: "json",
            api: 'yg_baijiaapporder/userAddress/addUserAddress',
            success: function (result) {
                if(result.code == 10000){
                    reAddressPage();        //回到地址列表页面
                    AddressPageNum = 1;     //获取地址列表从第一页开始
                    vm.addressList = [];
                    getAddressList();       //重新加载地址列表
                }else {
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        })
    }
}
var delAddList=[]
//删除地址
function delAddress(){
    YDUI.dialog.confirm('确定要删除该地址吗?', '', function () {
        //确定要删除该地址
        delAddList.push(vm.userAddressId);  //记录删除地址的收货ID
        $.ajaxHandler({
            model: function () {
                var obj={};
                obj.id = vm.userAddressId;
                obj.userId = userId;
                return obj;
            },
            visibleTime: 0,
            dataType: "json",
            api: 'yg_baijiaapporder/userAddress/removeUseraddressByuserId',
            success: function (result) {
                if(result.code == 10000){
                    //表示删除成功  重新获取地址列表
                    AddressPageNum = 1;
                    vm.addressList = [];
                    getAddressList();
                }else {
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        })
    });
}
//返回地址页面
function reAddressPage(){
    addListPage = true;
    $('.address-add').hide();
    $('.myAddress-wrap').show();
    $('.seleAddress').show();
    //改用户没有地址
    if(vm.addressList.length == 0){
        $('.addreddbg').show();
    }
}

//检查当前的地址  是否是已经删除的地址
function lookAddress(){
    var userAddressId = vm.addressObj.userAddressId;    //收货地址ID
    for(var i = 0,len = delAddList.length; i < len; i++){
        if(delAddList[i] == userAddressId){
            //说明之前选择的地址已经被删除
            vm.addressObj = {};
            getDefaultAddress();    //如果当前选择的地址 已经被删除 就选择默认地址
            break;
        }
    }
}
//编辑按钮打开的页面
function editBtn(){
    $('.payContent').hide();
    $('.address-add').show();
    $('.myAddress-wrap').hide();
    $('.seleAddress').hide();
    addListPage=false;
}
var address={};
var provances=[] ;    //省份的集合
var citys=[];         //城市的集合
function getAddress(){
    $.ajaxHandler({
        model: function () {
            var obj={};
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        visible:'hide',
        api: 'yg_baijiaapporder/userAddress/getProvinceCityArea',
        success:function(res){
            if(res.code==10000){
                var data=res.data;
                vm.addressInfo_list=res.data;
                data.forEach(function(value,index){
                    provances.push(value.proName)

                })
            }
        }
    })
}


//获得屏幕的宽高
var bh = $("body").height();
var bw = $("body").width();
//显示灰色 jQuery 遮罩层
function showBg() {
    $("#fullbg").css({
        height:bh,
        width:bw,
        display:"block",
    });
    $('.destinatioWrap').css({
        width:bw*1.5,
    })
    $('.destination .left').css({
        width:bw*0.5
    })
    $('body').css("overflow","hidden");

}

//关闭灰色 jQuery 遮罩
function closeBg(){
    $("#fullbg,#dialog").hide();
    $('body').css("overflow","visible")
}
